//
//  MPMineTaskController.m
//  MarkPlatform
//
//  Created by xiao6 on 2017/12/18.
//  Copyright © 2017年 AT. All rights reserved.
//

#import "MPMineTaskController.h"
#import "MPMyTaskCell.h"
#import "MPMyTaskLayout.h"
#import "MPMyTaskInfoController.h"

@interface MPMineTaskController (){
    CGFloat _dragStartX;
    CGFloat _dragEndX;
    BOOL _hasMore;
}
@property (nonatomic, assign, readwrite) NSInteger selectedIndex;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *bottomButton;
@property (nonatomic, strong) NSMutableArray *dataList;
@end

@implementation MPMineTaskController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupRefresh:self.collectionView option:ATRefreshDefault];
    [self setupEmpty:self.collectionView];
    [self setupViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self updateActions];
    MPTaskModel *taskModel = self.currentTask;
    if (taskModel && taskModel.status != self.state) {
        [self.collectionView performBatchUpdates:^{
            [self.dataList removeObject:taskModel];
            [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]]];
            [self updateActions];
        } completion:nil];
    }
}

- (void)refreshData:(NSInteger)page {
    [MPHttpTool POST:@"business/task/queryMyTask"
              params:@{@"userid" : SafeDicObj([ATLocal user].userId),
                       @"page":@(page),
                       @"rows":@(RefreshPageSize),
                       @"status":@(self.state)}
             success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                 ATRefreshModel *model = [ATRefreshModel modelWithJSON:result.data];
                 if (page == RefreshPageStart) {
                     self.dataList = [NSMutableArray array];
                 }
                 [self.dataList addObjectsFromArray:[MPTaskModel modelArrayWithJson:model.rows]];
                 [self.collectionView reloadData];
                 _hasMore = model.total > self.dataList.count;
                 [self endRefreshNeedHidden:NO];
                 [self updateActions];
             } failure:ATDefaultFailure];
}

#pragma mark - actions
- (MPTaskModel *)currentTask {
    return [self.dataList objectSafeAtIndex:self.selectedIndex];
}

- (void)updateActions {
    if (_hasMore && !self.isRefreshing && self.selectedIndex + 2 > self.dataList.count) {
        [self footerRefreshing];
    }
    
    if (!self.viewIsAppear) {
        return;
    }
    MPTaskModel *task = self.currentTask;
    if (!task) {
        self.bottomButton.hidden = YES;
        [UIViewController rootTopPresentedController].navigationItem.rightBarButtonItem = nil;
        return;
    }
    
    self.bottomButton.hidden = NO;
    if (task.hasCancel) {
        self.bottomButton.enabled = task.cancel;
        [self.bottomButton setTitle:@"取消" forState:UIControlStateNormal];
        [self.bottomButton setTarget:self action:@selector(cancleCurrentTask) forControlEvents:UIControlEventTouchUpInside];
        [UIViewController rootTopPresentedController].navigationItem.rightBarButtonItem = [self navItemWithImage:[UIImage imageNamed:@"nav_icon_delete_nor"] action:@selector(deleteCurrentTask)];
    }
    else {
        [self.bottomButton setTitle:@"删除当前任务" forState:UIControlStateNormal];
        [self.bottomButton setTarget:self action:@selector(deleteCurrentTask) forControlEvents:UIControlEventTouchUpInside];
        [UIViewController rootTopPresentedController].navigationItem.rightBarButtonItem = nil;
    }
}

- (void)cancleCurrentTask {
    MPTaskModel *taskModel = self.currentTask;
    if (!taskModel) {
        return;
    }
    [ATAlertView showTitle:@"任务取消后无法获得佣金,是否取消任务?" message:nil normalButtons:@[@"取消"] highlightButtons:@[@"确定"] completion:^(NSInteger index, NSString *buttonTitle) {
        if (index <= 0) {
            return;
        }
        [MPHttpTool GET:[NSString stringWithFormat:@"business/task/cancel/%@", taskModel.Id]
                 params:nil
                success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                    [MBProgressHUD showMessage:@"取消成功"];
                    [self.collectionView performBatchUpdates:^{
                        [self.dataList removeObject:taskModel];
                        [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]]];
                        [self updateActions];
                    } completion:nil];
                }
                failure:ATDefaultFailure];
    }];
}
- (void)deleteCurrentTask {
    MPTaskModel *taskModel = self.currentTask;
    if (!taskModel) {
        return;
    }
    [ATAlertView showTitle:@"是否删除任务?" message:nil normalButtons:@[@"取消"] highlightButtons:@[@"确定"] completion:^(NSInteger index, NSString *buttonTitle) {
        if (index <= 0) {
            return;
        }
        [MPHttpTool GET:[NSString stringWithFormat:@"business/task/delete/%@",taskModel.Id]
                 params:nil
                success:^(NSURLSessionDataTask *task, ATApiResult *result) {
                    [MBProgressHUD showMessage:@"删除成功"];
                    [self.collectionView performBatchUpdates:^{
                        [self.dataList removeObject:taskModel];
                        [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]]];
                    } completion:nil];
                    [self updateActions];
                } failure:ATDefaultFailure];
    }];
}

#pragma mark - delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MPMyTaskCell *cell =  [MPMyTaskCell cellForCollectionView:collectionView indexPath:indexPath];
    cell.model = self.dataList[indexPath.row];
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!self.collectionView.visibleCells.count) {return;}
    if (!scrollView.isDragging) {return;}
    CGRect currentRect = self.collectionView.bounds;
    currentRect.origin.x = self.collectionView.contentOffset.x;
    for (MPMyTaskCell *cell in self.collectionView.visibleCells) {
        if (CGRectContainsRect(currentRect, cell.frame)) {
            NSInteger index = [self.collectionView indexPathForCell:cell].row;
            if (index != _selectedIndex) {
                _selectedIndex = index;
            }
        }
    }
}
//手指拖动开始
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _dragStartX = scrollView.contentOffset.x;
}
//手指拖动停止
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _dragEndX = scrollView.contentOffset.x;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self fixCellToCenter];
    });
}
//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _selectedIndex = indexPath.row;
    [self scrollToCenter];
    [[self.view getNavigationController] pushViewController:[MPMyTaskInfoController vcWithTaskModel:self.dataList[indexPath.row]] animated:YES];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}

#pragma mark - privite
//配置cell居中
- (void)fixCellToCenter {
    //最小滚动距离
    float dragMiniDistance = self.collectionView.bounds.size.width/20.0f;
    if (_dragStartX -  _dragEndX >= dragMiniDistance) {
        _selectedIndex -= 1;//向右
    }else if(_dragEndX -  _dragStartX >= dragMiniDistance){
        _selectedIndex += 1;//向左
    }
    NSInteger maxIndex = [self.collectionView numberOfItemsInSection:0] - 1;
    _selectedIndex = _selectedIndex <= 0 ? 0 : _selectedIndex;
    _selectedIndex = _selectedIndex >= maxIndex ? maxIndex : _selectedIndex;
    [self scrollToCenter];
}
// 滚动到中间
- (void)scrollToCenter {
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_selectedIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [self updateActions];
}
- (void)setSelectedIndex:(NSInteger)selectedIndex {
    [self switchToIndex:selectedIndex animated:false];
}
- (void)switchToIndex:(NSInteger)index animated:(BOOL)animated {
    _selectedIndex = index;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animated];
    [self updateActions];
}

#pragma mark - setupViews
- (void)setupViews {
    self.collectionView.backgroundColor = [UIColor colorWithRGB:0xF3F3F3];
    self.view.backgroundColor = self.collectionView.backgroundColor;
    
    MPMyTaskLayout *layout = [[MPMyTaskLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.alwaysBounceVertical = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        CGFloat cellWidth = SCREEN_WIDTH * 630.f/750;
        CGFloat cellHeight = cellWidth / (630.f/900);
        make.height.equalTo(@(cellHeight + 20));
    }];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.bottomButton];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(self.collectionView.mas_bottom);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.height.equalTo(@(45.0f));
        make.width.equalTo(@(SCALEW(200)));
        make.centerY.offset(-8);
    }];
}

#pragma mark - getters
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
    }
    return _bottomView;
}
- (UIButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [MPAppButton buttonWithTitle:@"删除当前任务" target:self action:@selector(deleteCurrentTask)];
        _bottomButton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
        _bottomButton.hidden = YES;
    }
    return _bottomButton;
}
- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

@end




